<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="合同编号" prop="vBillNo">
        <el-input
          v-model="queryParams.vBillNo"
          placeholder="请输入合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目号" prop="vProjectNo">
        <el-input
          v-model="queryParams.vProjectNo"
          placeholder="请输入项目号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="vProjectDec">
        <el-input
          v-model="queryParams.vProjectDec"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商" prop="supplier">
        <el-input
          v-model="queryParams.supplier"
          placeholder="请输入供应商"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="vBrand">
        <el-input
          v-model="queryParams.vBrand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applyBy">
        <el-input
          v-model="queryParams.applyBy"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable>
          <el-option
            v-for="dict in dict.type.buy_contract_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleImport"
          >外采合同导入</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button size="mini" @click="linkToPost">合并发货</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="billList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        type="index"
        label="序号"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column label="合同类型" prop="vType" width="80px">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.spa_spa_kind"
            :value="scope.row.vType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="合同编号"
        align="center"
        prop="vBillNo"
        width="120px"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="toDetail(scope.row)">
            {{ scope.row.vBillNo }}</el-button
          >
        </template>
      </el-table-column>

      <el-table-column label="品牌" align="center" prop="vBrand" />
      <el-table-column label="供应商/厂家" align="center" prop="supplier" />
      <el-table-column label="货期" align="center" prop="nDays" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.buy_contract_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-if="scope.row.status == '0'"
            size="mini"
            type="text"
            @click="handleToDone(scope.row)"
            >处理完成</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【外购合同】对话框 -->
    <el-drawer
      :title="title"
      :before-close="handleClose"
      :visible.sync="open"
      size="70%"
      ref="drawer"
    >
      <div class="drawer-container">
        <div class="xin-main">
          <div class="xin-content" style="height: 90%">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同编号" prop="vBillNo">
                    <el-input
                      v-model="form.vBillNo"
                      placeholder="请输入合同编号"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="品牌" prop="vBrand">
                    <el-input v-model="form.vBrand" placeholder="请输入品牌" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="供应商" prop="supplier">
                    <el-input
                      v-model="form.vBrand"
                      placeholder="请输入供应商"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="货期" prop="nDays">
                    <el-input v-model="form.nDays" placeholder="请输入货期" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-divider content-position="left"></el-divider>
            <el-table :data="itemList" height="450px">
              <el-table-column
                label="序号"
                align="center"
                type="index"
                prop="index"
              />
              <el-table-column label="请购单号" align="center" prop="vBuyNo" />
              <el-table-column
                label="项目号"
                align="center"
                prop="vProjectNo"
              />
              <el-table-column
                label="项目名称"
                align="center"
                prop="vProjectDec"
              />
              <el-table-column
                label="物料名称"
                align="center"
                prop="vSpaName"
              />
              <el-table-column
                label="规格型号"
                align="center"
                prop="vSpaModel"
                width="200px"
              />
              <el-table-column label="品牌" align="center" prop="vSpaBrand" />
              <!-- <el-table-column label="单位" align="center" prop="vUnit" /> -->
              <el-table-column label="单价" align="center" prop="nPrice">
                <template slot-scope="scope">
                  <el-input size="small" v-model="scope.row.nPrice"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="nQty" />
              <el-table-column
                label="供应商"
                align="supplier"
                prop="supplier"
                width="200px"
              />
              <el-table-column label="货期" align="nDays" prop="nDays" />
              <el-table-column label="备注" align="center" prop="remark" />
            </el-table>
            <div
              class="xin-footer"
              style="position: fixed; bottom: 5px; right: 10px"
            >
              <el-button
                v-if="form.status == '0'"
                type="primary"
                @click="submitForm('02')"
                >确 定</el-button
              >
              <el-button @click="cancel('02')">取 消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 添加或修改【机加合同】对话框 -->
    <el-drawer
      :title="titleJijia"
      :visible.sync="openJijia"
      size="50%"
      ref="drawer"
    >
      <div class="drawer-container">
        <div class="xin-main">
          <div class="xin-content" style="height: 90%">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合同编号" prop="vBillNo">
                    <el-input
                      v-model="form.vBillNo"
                      placeholder="请输入合同编号"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目号" prop="vProjectNo">
                    <el-input
                      v-model="form.vProjectNo"
                      placeholder="请输入项目号"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="vProjectDec">
                    <el-input
                      v-model="form.vProjectDec"
                      placeholder="请输入项目名称"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="厂家" prop="supplier">
                    <el-input
                      v-model="form.supplier"
                      placeholder="请输入厂家"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="设计人" prop="applyBy">
                    <el-input
                      v-model="form.applyBy"
                      placeholder="请输入设计人"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-divider content-position="left"></el-divider>
            <el-table :data="itemList" height="450px">
              <el-table-column
                label="序号"
                align="center"
                type="index"
                prop="index"
              />
              <el-table-column
                label="零件名称"
                align="center"
                prop="vSpaName"
              />
              <el-table-column
                label="零件号/图纸号"
                align="center"
                prop="vSpaModel"
                width="200px"
              />
              <el-table-column label="材料" align="center" prop="vSpaBrand" />
              <el-table-column
                label="合同额单价含税（元）"
                align="center"
                prop="nPrice"
              />
              <el-table-column label="数量" align="center" prop="nQty" />
              <el-table-column
                label="供应商"
                align="supplier"
                prop="supplier"
                width="200px"
              />
              <el-table-column label="备注" align="center" prop="remark" />
            </el-table>
            <div slot="footer" class="drawer-footer">
              <el-button type="primary" @click="submitForm('01')"
                >确 定</el-button
              >
              <el-button @click="cancel('02')">取 消</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size: 12px" @click="importTemplate"
            >下载模板</el-link
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="维护发票信息"
      :visible.sync="invoiceOpen"
      width="500px"
      append-to-body
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleInvoiceAdd"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="invoiceList" border height="400px">
        <el-table-column
          type="index"
          label="序号"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          width="300px"
          prop="vInvocieNo"
          label="发票号"
        >
          <template slot-scope="scope">
            <el-input size="small" v-model="scope.row.vInvocieNo"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              @click="handleInvDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInvoice">确 定</el-button>
        <el-button @click="cancelInvoice">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBill,
  getBill,
  delBill,
  addBill,
  updateBill,
  getInvoiceInfo,
  delInvoice,
  saveInvoice,
  updateBillStatus,
} from "@/api/buy/buy0003";
import { getToken } from "@/utils/auth";

export default {
  name: "Bill",
  dicts: [
    "sys_normal_disable",
    "spa_spa_kind",
    "buy_contract_type",
    "buy_contract_status",
  ],
  data() {
    return {
      // 遮罩层
      loading: true,
      insertFlag: false,
      invoiceOpen: false,
      // 选中数组
      ids: [],
      vBillNos: [],
      vProjectNos: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      billList: [],
      // 弹出层标题
      title: "",
      titleJijia: "",
      // 是否显示弹出层
      open: false,
      openJijia: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        vBillNo: null,
        status: null,
        vProjectNo: null,
        vProjectDec: null,
        applyBy: null,
        oprBy: null,
        supplier: null,
        nAmt: null,
        nDays: null,
        vBrand: null,
      },
      // 表单参数
      form: {
        id: null,
        vBillNo: null,
        status: null,
        vProjectNo: null,
        vProjectDec: null,
        delFlag: null,
        applyBy: null,
        oprBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        supplier: null,
        nAmt: null,
        nDays: null,
      },
      // 表单校验
      rules: {
        nAmt: [
          { required: true, trigger: "blur", message: "合同金额不能为空" },
        ],
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/buy/buy0003/importData",
      },
      itemList: [],
      invoiceList: [],
      clickInvoiceRow: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listBill(this.queryParams).then((response) => {
        this.billList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vBillNo: null,
        status: null,
        vProjectNo: null,
        vProjectDec: null,
        delFlag: null,
        applyBy: null,
        oprBy: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        supplier: null,
        nAmt: null,
        nDays: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.vBillNos = selection.map((item) => item.vBillNo);
      this.vProjectNos = selection.map((item) => item.vProjectNo);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购合同";
      this.insertFlag = false;
    },
    toDetail(row) {
      let params = row;

      this.$router.push({
        name: "detail",
        params: params,
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getBill(id).then((response) => {
        this.form = response.data.billPO;
        this.itemList = response.data.itemPOList;
        if (row.vType == "02") {
          this.open = true;
          this.title = "修改外购合同";
        } else if (row.vType == "01") {
          this.openJijia = true;
          this.titleJijia = "修改机加合同";
        }
      });
      this.insertFlag = true;
    },
    /** 提交按钮 */
    submitForm(type) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          addBill({ billPO: this.form, itemPOList: this.itemList }).then(
            (response) => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            }
          );
        }
      });
    },
    /** 删除按钮操作 */
    handleToDone(row) {
      this.$modal
        .confirm("是否确认该合同已经完成？")
        .then(function () {
          return updateBillStatus(row);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("处理成功");
        })
        .catch(() => {});
    },
    updateBillStatus(row) {
      updateBillStatus(row).then((response) => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "buy/buy0003/export",
        {
          ...this.queryParams,
        },
        `bill_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "合同明细导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "buy/buy0003/importTemplate",
        {},
        `合同明细_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log("--------------------------------");
      console.log(response);
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 发票信息按钮操作 */
    handleInvoice(row) {
      this.clickInvoiceRow = row;
      getInvoiceInfo({ nMainId: row.id, status: 0, delFlag: 0 }).then(
        (response) => {
          this.invoiceList = response.data;
          this.invoiceOpen = true;
        }
      );
    },
    //新增发票信息
    handleInvoiceAdd() {
      var _this = this;
      let list = {
        vInvoiceNo: "",
        status: 0,
        delFlag: "0",
      };

      _this.invoiceList.push(list);
    },

    /** 删除发票按钮操作 */
    handleInvDelete(index, row) {
      debugger;
      var _this = this;
      this.$modal
        .confirm("是否确认删除该条数据项？")
        .then(function () {
          debugger;
          if (
            row.id === "" ||
            row.id === null ||
            row.id === undefined ||
            row.id === 0
          ) {
          } else {
            return delInvoice(row);
          }
        })
        .then(() => {
          _this.invoiceList.splice(index, 1);
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 删除发票按钮操作 */
    submitInvoice() {
      saveInvoice({
        billPO: this.clickInvoiceRow,
        invoiceList: this.invoiceList,
      }).then((response) => {
        this.invoiceOpen = false;
        this.getList();
      });
    },
    cancelInvoice() {
      this.invoiceOpen = false;
    },
    handleClose() {
      this.open = false;
      this.getList();
    },
    linkToPost() {
      let params = {
        ids: this.ids,
        vBillNos: this.vBillNos,
        vProjectNos: this.vProjectNos,
      };

      this.$router.push({
        name: "post",
        params: params,
      });
    },

    linkToPostRow(row) {
      let params = {
        ids: [row.id],
        vBillNos: [row.vBillNo],
        vProjectNos: [row.vProjectNo],
      };
      console.log("$$$$$$$$$$$$");
      console.log(params);
      this.$router.push({
        name: "post",
        params: params,
      });
    },
  },
};
</script>
<style>
.xin-main {
  position: relative;
  height: 100%;
  overflow: hidden;
}
.xin-content {
  overflow-y: scroll;
  box-sizing: border-box;
  overflow-x: hidden;
}
</style>
